import * as http from 'http';
import {IncomingMessage, ServerResponse} from 'http';
import * as p from 'path';
import * as fs from 'fs';

const server = http.createServer();
const publicDir = p.resolve(__dirname, 'public');
let cacheAge = 3600*24*365
server.on('request', (request: IncomingMessage, response: ServerResponse) => {
  const {method} = request
  if (method !== 'GET'){
    response.statusCode = 405
    response.end()
    return
  }
  const myURL = new URL(request.url, `http://${request.headers.host}`);
  const {pathname} = myURL;
  let fileName = pathname==='/'?'index.html':pathname.substring(1);
  // response.setHeader('Content-Type', 'text/html; charset=utf-8');
  fs.readFile(p.resolve(publicDir, fileName), (error, data) => {
    if (error) {
      if (error.errno === -4058) {
        response.statusCode = 404;
        fs.readFile(p.resolve(publicDir, '404.html'), (error404, data404) => {
          if (error404) throw error;
          response.end(data404);
        });
      }
    } else {
      response.setHeader('Cache-Control',`public, max-age=${cacheAge}`)
      response.end(data);
    }
  });
});
server.listen('8888');






